﻿using System;
using System.Data;
using System.Windows.Forms;
using DbManager;
using DbManager.DataManager;
using DbManager.QueryBuilder.DbEntity.IND.Uslovia;

namespace TAProject.UI.Service.Terms
{
    public partial class FormManageUslovia : FormTemplate
    {
        private readonly Form _parentForm;
        private readonly IDataManager _dataManager;
        private readonly IConnectionManager _connectionManager;
        private readonly AEntityUslovia _aEntityUslovia;

        private int _currentRowIndex;
        private DataTable _dataTableMain;

        public FormManageUslovia(Form parentForm, IDataManager dataManager, IConnectionManager connectionManager)
            : base(parentForm)
        {
            InitializeComponent();

            _parentForm = parentForm;
            _dataManager = dataManager;
            _connectionManager = connectionManager;

            _aEntityUslovia = new EntityUslovia();
            UpdateDataGrid();

            _parentForm.Enabled = false;
        }

        private void ButtonCloseClick(object sender, EventArgs e)
        {
            FormClose();
        }

        private void FormClose()
        {
            _parentForm.Enabled = true;
            Close();
        }

        private void DataGridViewCellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dataGridView.CurrentRow == null || dataGridView.CurrentRow.Index < 0) return;
            _currentRowIndex = dataGridView.CurrentRow.Index;
        }

        private void FormManageUslovia_EnabledChanged(object sender, EventArgs e)
        {
            if (dataGridView.Rows.Count > 0)
            {
                dataGridView.Rows[_currentRowIndex].Selected = true;
            }
        }

        #region Buttons events

        private void ButtonAddClick(object sender, EventArgs e)
        {
            var form = new FormNameDescription(this, _dataManager, _connectionManager, new EntityUslovia(), false);
            form.ShowDialog(this);
            UpdateDataGrid();
        }

        private void ButtonEditClick(object sender, EventArgs e)
        {
            if (dataGridView.CurrentRow != null)
            {
                _aEntityUslovia.ID = (int)dataGridView.Rows[_currentRowIndex].Cells["Hide_ID"].Value;
                _aEntityUslovia.Name = dataGridView.Rows[_currentRowIndex].Cells["Название"].Value.ToString();
                _aEntityUslovia.Description = dataGridView.Rows[_currentRowIndex].Cells["Описание"].Value.ToString();

                var form = new FormNameDescription(this, _dataManager, _connectionManager, _aEntityUslovia, true);
                form.ShowDialog(this);

                UpdateDataGrid();
            }
            
        }

        private void ButtonDeleteClick(object sender, EventArgs e)
        {
            if (dataGridView.CurrentRow != null)
            {
                _aEntityUslovia.ID = (int)dataGridView.Rows[_currentRowIndex].Cells["Hide_ID"].Value;
                var rowAffected = _dataManager.ManageDataInDb(_aEntityUslovia.GetDeleteQuery(), _connectionManager.GetConnection());
                if (rowAffected == 0)
                {
                    MessageBox.Show("Ошибка удаления, повторите попытку.");
                }
            }
            UpdateDataGrid();
        }

        #endregion

        private void UpdateDataGrid()
        {
            if (_connectionManager.CheckConnection())
            {
                _dataTableMain = _dataManager.GetDataTable(_aEntityUslovia.GetSelectQuery(),
                                                           _connectionManager.GetConnection());
                if (_dataTableMain != null)
                {
                    FillDataGrid();
                    _currentRowIndex = 0;
                }
                else
                {
                    MessageBox.Show("Данные отсутствуют.");
                }
            }
            else
            {
                MessageBox.Show("Ошибка подключения к БД.");
                FormClose();
            }
        }

        private void FillDataGrid()
        {
            if (_dataTableMain.Rows.Count > 0)
            {
                buttonDelete.Enabled = true;
                buttonEdit.Enabled = true;
                CustomFillDataGrid(_dataTableMain);
            }
            else
            {
                buttonDelete.Enabled = false;
                buttonEdit.Enabled = false;
                CustomFillDataGrid(_dataTableMain);
                MessageBox.Show("Данные отсутствуют");
            }
        }

        private void CustomFillDataGrid(DataTable dataTable)
        {
            if (dataTable != null)
            {
                dataGridView.DataSource = dataTable;
                //скрываем все ненужные столбцы
                for (var i = 0; i < dataGridView.Columns.Count; i++)
                {
                    if (dataGridView.Columns[i].Name.StartsWith("Hide"))
                    {
                        dataGridView.Columns[i].Visible = false;
                    }
                }
            }
            else
            {
                MessageBox.Show("Данные отсутствуют.");
            }
        }
    }
}